package com.yy.wga.common.util.sign;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

/**
 * Md5Utils
 *
 * @author lgw
 */
@Slf4j
public class Md5Utils {
    /**
     * 加盐数组长度
     */
    private static final int SALT_LENGTH = 9;

    /**
     * 加盐密码验证合法性
     *
     * @param password
     * @param salt
     * @param saltPassword
     * @return
     */
    public static boolean validatePassword(String password, String salt, String saltPassword) {
        if (StrUtil.isNotBlank(password) && StrUtil.isNotBlank(salt) && StrUtil.isNotBlank(saltPassword)) {
            String saltPsw = getMd5(salt + password);
            if (saltPassword.equals(saltPsw)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 生成加盐密码
     *
     * @param password
     * @param salt
     * @return
     */
    public static String saltPassword(String password, String salt) {
        return getMd5(salt + password);
    }

    /**
     * 生成加盐值
     *
     * @return
     */
    public static String getSalt() {
        //随机数生成器
        SecureRandom random = new SecureRandom();
        //声明盐数组变量
        byte[] salt = new byte[SALT_LENGTH];
        //将随机数放入盐变量中
        random.nextBytes(salt);
        return bytesToHexString(salt);
    }

    /**
     * 获取md5加密字符串
     *
     * @param sign
     * @return
     * @throws NoSuchAlgorithmException
     */
    public static String getMD5(byte[] sign) throws NoSuchAlgorithmException {

        MessageDigest md5 = MessageDigest.getInstance("MD5");

        byte[] md5Bytes = md5.digest(sign);
        StringBuffer hexValue = new StringBuffer();
        for (int i = 0; i < md5Bytes.length; i++) {
            int val = ((int) md5Bytes[i]) & 0xff;
            if (val < 16) {
                hexValue.append("0");
            }
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString().toLowerCase();

    }

    /**
     * 功能描述:
     * 获取 MD5字符串
     *
     * @参 数: 原始字符串
     * @返 回: MD字符串
     * @日 期: 2018/11/16 10:41:26
     */
    public static String getMd5(String key) {
        String cacheKey;
        try {
            final MessageDigest digest = MessageDigest.getInstance("MD5");
            digest.update(key.getBytes());
            cacheKey = bytesToHexString(digest.digest());
        } catch (NoSuchAlgorithmException e) {
            cacheKey = String.valueOf(key.hashCode());
        }
        return cacheKey;
    }

    private static String bytesToHexString(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(0xFF & bytes[i]);
            if (hex.length() == 1) {
                sb.append('0');
            }
            sb.append(hex);
        }
        return sb.toString();
    }
}

